package com.sejong.andproject2;



import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.Vector;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gcm.GCMRegistrar;

public class MainActivity extends Activity implements LocationListener{
	private LocationManager mLocationManager;
	Geocoder mGeocoder;
	private Location mLocation = null;
	private double Latitude;
	private double Loongitude;
	private String TAG = "** pushAndroidActivity **";
	public static String SENDER_ID = "236895394554";
	Handler handler = new Handler();
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);
        
        setContentView(R.layout.activity_main);
        
        final String regId = GCMRegistrar.getRegistrationId(this);
        Log.i(TAG, "registration id ====&nbsp;" + regId);
        
        if(regId.equals("")){
     	   GCMRegistrar.register(this, SENDER_ID);
     	   
        }else{
     	   
     	   Log.v(TAG,"Already registered");
        }
        
        
        mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        mGeocoder = new Geocoder(this, Locale.KOREAN);
        
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.NO_REQUIREMENT);
        criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
        
        String provider = mLocationManager.getBestProvider(criteria,true);
        mLocationManager.requestLocationUpdates(provider, 1000, 5, this);
        
        mLocation = mLocationManager.getLastKnownLocation(provider);
        updateWithNewLocation(mLocation);
        
        httpsend httpsend1 = new httpsend();
        httpsend1.start();
        
        Button btn01 = (Button)findViewById(R.id.btn01);
        btn01.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				Intent intent = new Intent(MainActivity.this,shakingPhoneCall.class);
				startActivity(intent);
				
				
			}
        	
        });
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub
		updateWithNewLocation(arg0);
	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		updateWithNewLocation(null);
	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	
	private void updateWithNewLocation(Location location){
			String mLatLoString;
			TextView mTextView = (TextView)findViewById(R.id.textview01);
			
			if(location != null){
				Latitude = location.getLatitude();
				Loongitude = location.getLongitude();
				//feed();
				//sendToServer(Latitude,Loongitude);
				mLatLoString = "Latitue : "+ Latitude + "\n Longitude : " + Loongitude;
			}else{
				mLatLoString = "Can't find your location";
				
			}
			mTextView.setText("Location : " + mLatLoString);
			
		
	}
	
	private String sendToServer(double lat, double lon) throws ClientProtocolException, IOException{
		String latitude = Double.toString(lat);
		String longitude = Double.toString(lon);
		
		HttpPost request = makeHttpPost(latitude,longitude,"http://comms2012.dothome.co.kr/project/getUserLocaion.php");
		
		HttpClient client = new DefaultHttpClient();
		ResponseHandler<String> reshandler = new BasicResponseHandler();
		String result = client.execute(request,reshandler);
		return result;
		
	}
	private HttpPost makeHttpPost(String $longitude, String $latitude, String $url){
		HttpPost request = new HttpPost($url);
		Vector<NameValuePair> nameValue = new Vector<NameValuePair>();
		nameValue.add(new BasicNameValuePair("latitude", $latitude));
		nameValue.add(new BasicNameValuePair("longitude",$longitude));
		request.setEntity(makeEntity(nameValue));
		
		
		
		return request;
		
		
	}
	private HttpEntity makeEntity(Vector<NameValuePair> $namevalue){
		HttpEntity result = null;
		
		try{
			
			result = new UrlEncodedFormEntity($namevalue);
			
		}catch(UnsupportedEncodingException e){
			e.printStackTrace();
			
		}
		
		return result;
		
		
	}
	public class httpsend extends Thread{
		//TextView textview02 = (TextView)findViewById(R.id.textview02);
		String loginfo;
		public void run(){
			   try {
					loginfo = sendToServer(Latitude,Loongitude);
					Log.i("RESPONSE : ", loginfo);
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		
			
		}
	  }
	}
